package files

import (
	"strings"

	"clouds.lgb24kcs.cn/controllers/files/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/history"
	"clouds.lgb24kcs.cn/utils/oss"
	"github.com/gin-gonic/gin"
)

type FileApi struct {
}

var File FileApi

func (a *FileApi) Create(c *gin.Context, req request.UploadFileReq, file_dir, file string, userId int64, Size int64) {

	BucketInfo := models.Storage{}
	api := oss.OSS{}
	tx := global.APP.DB.Where("id=? AND userid=?", req.BucketID, userId).First(&BucketInfo)
	if tx.Error != nil {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.ObjectCreate, tx.Error.Error())
	} else {
		svc := api.NewClient(BucketInfo.Accesskey, BucketInfo.Secretkey, BucketInfo.Zone)

		if err := api.UploadFile(svc, req.BucketName, req.CatalogueName, file_dir, file); err != nil {
			global.APP.Log.Error(err.Error())
		} else {
			if BucketInfo.DomainName == "" {
				BucketInfo.DomainName = global.APP.Configuration.Server.LOCAL + ":" + "9000" + "/" + req.BucketName + "/"
			}
			objectURL := "http://" + BucketInfo.DomainName + req.CatalogueName + "/" + file
			file_type := strings.Split(file, ".")[len(strings.Split(file, "."))-1] // 获得切片的最后一个元素的下标

			fileinfo := models.Files{
				RootDir:    req.CatalogueName,
				Bucketname: req.BucketName,
				Filename:   file,
				UserId:     userId,
				FileLink:   objectURL,
				Type:       file_type,
				Size:       Size,
			}
			tx = global.APP.DB.Create(&fileinfo)
			if tx.Error != nil {
				if err = api.DelObject(svc, req.BucketName, req.CatalogueName+"/"+file); err != nil {
					utils.Fail(c, errorx.ObjectCreate, tx.Error.Error())
				}
			} else {
				/*这里需要将上传成功的文件删除*/
				// 记录操作历史
				userId = utils.CtxUserId(c)
				if err = history.HistoryCreate(userId, c.Request.Method, c.Request.URL.String(), c.Request.Host); err != nil {
					utils.Fail(c, errorx.ObjectSearch, err.Error())

				} else {
					utils.Success(c, 0, "上传成功")
				}
			}
		}
	}
}
